import { Request, Response, NextFunction } from 'express'
import { AuthService } from '../services/authService'

// 扩展Request接口以包含用户信息
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: string
        email?: string
        phone?: string
        username?: string
        is_verified: boolean
        login_type: string
      }
      userId?: string
    }
  }
}

// JWT认证中间件
export const authenticateToken = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization
    const token = authHeader && authHeader.split(' ')[1] // Bearer TOKEN
    
    if (!token) {
      return res.status(401).json({ 
        error: 'ACCESS_TOKEN_REQUIRED',
        message: '需要提供访问令牌' 
      })
    }
    
    const decoded = AuthService.verifyToken(token)
    if (!decoded) {
      return res.status(403).json({ 
        error: 'INVALID_TOKEN',
        message: '无效的访问令牌' 
      })
    }
    
    // 获取用户信息
    const user = await AuthService.getUserById(decoded.userId)
    if (!user) {
      return res.status(403).json({ 
        error: 'USER_NOT_FOUND',
        message: '用户不存在' 
      })
    }
    
    // 将用户信息添加到请求对象
    req.user = user
    req.userId = user.id
    
    next()
  } catch (error) {
    console.error('认证中间件错误:', error)
    res.status(500).json({ 
      error: 'AUTH_ERROR',
      message: '认证失败' 
    })
  }
}

// 可选认证中间件（不强制要求登录）
export const optionalAuth = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization
    const token = authHeader && authHeader.split(' ')[1]
    
    if (token) {
      const decoded = AuthService.verifyToken(token)
      if (decoded) {
        const user = await AuthService.getUserById(decoded.userId)
        if (user) {
          req.user = user
          req.userId = user.id
        }
      }
    }
    
    next()
  } catch (error) {
    // 可选认证失败不影响请求继续
    console.warn('可选认证失败:', error)
    next()
  }
}

// 验证邮箱格式
export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 验证手机号格式
export const validatePhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

// 验证密码强度
export const validatePassword = (password: string): { valid: boolean; message?: string } => {
  if (password.length < 6) {
    return { valid: false, message: '密码长度至少6位' }
  }
  
  if (password.length > 128) {
    return { valid: false, message: '密码长度不能超过128位' }
  }
  
  // 可以添加更多密码强度要求
  // if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
  //   return { valid: false, message: '密码必须包含大小写字母和数字' }
  // }
  
  return { valid: true }
}

// 限流中间件（防止暴力破解）
const attemptCounts = new Map<string, { count: number; resetTime: number }>()

export const rateLimiter = (maxAttempts: number = 5, windowMinutes: number = 15) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const identifier = req.ip || 'unknown'
    const now = Date.now()
    const windowMs = windowMinutes * 60 * 1000
    
    const current = attemptCounts.get(identifier)
    
    if (!current || now > current.resetTime) {
      // 重置计数
      attemptCounts.set(identifier, { count: 1, resetTime: now + windowMs })
      next()
    } else if (current.count < maxAttempts) {
      // 增加计数
      current.count++
      next()
    } else {
      // 超过限制
      res.status(429).json({
        error: 'TOO_MANY_ATTEMPTS',
        message: `请求过于频繁，请${windowMinutes}分钟后再试`,
        retryAfter: Math.ceil((current.resetTime - now) / 1000)
      })
    }
  }
}
